import { useEffect, useRef, useState } from "react";

const useCount = (value) => {
    const [count, setCount] = useState(value);
    const [isRun, setIsRun] = useState(false);
    const timer = useRef(null)

    const startRun = () => {
        setIsRun(true);
        timer.current = setInterval(() => {
            setCount((prveCount) => {
                const nCount = prveCount - 1;

                if(nCount <= 0) {
                    clearInterval(timer.current);
                    setIsRun(false);
                    setCount(value);
                }

                return nCount;
            })
        }, 1000)
    }

    useEffect(() => {
        return () => {
            clearInterval(timer.current);
        }
    }, [])

    return {isRun, startRun, count}
}

export default useCount;